package com.flute.icrawler.framework.autoadjust.strategy;

import org.apache.log4j.Logger;

import com.flute.icrawler.app.service.CrawlService;
import com.flute.icrawler.framework.autoadjust.FetchAdjuster;
import com.flute.icrawler.framework.autoadjust.IAdjusterStrategy;

/**
 * 根据cpu,内存,硬盘的使用情况实时调整爬虫的处理能力
 * 
 * @author wangbin
 * 
 */
public class HardwareFetchAdjusterStrategy implements IAdjusterStrategy {
	private static final Logger LOGGER = Logger.getLogger(HardwareFetchAdjusterStrategy.class);
	private FetchAdjuster fetchAdjuster = null;
	private double cpuRate;
	private double memoryRate;
	private int interval;

	/**
	 * 
	 * @param fetchAdjuster
	 */
	public HardwareFetchAdjusterStrategy(FetchAdjuster fetchAdjuster) {
		this.fetchAdjuster = fetchAdjuster;
	}

	@Override
	public void doAdjust() {
		this.init();

		if (cpuRate > 0.9 || memoryRate > 0.9) {
			this.changInterval(2.0);
		} else if (cpuRate > 0.5 && cpuRate < 0.7 && memoryRate > 0.5 && memoryRate < 0.7) {
			this.changInterval(1.1);
		} else if (cpuRate < 0.5 && memoryRate < 0.5) {
			this.changInterval(0.9);
		}
	}

	@Override
	public void afterAdjust() {
		// TODO Auto-generated method stub

	}

	/**
	 * 
	 */
	private void init() {
		this.cpuRate = CrawlService.getOSCpuRate();
		this.memoryRate = CrawlService.getOSMemoryRate();
		this.interval = fetchAdjuster.getInterval();
	}

	/**
	 * 
	 * @param interval
	 */
	public void changInterval(double rate) {
		int interval = (int) (this.interval * rate);
		fetchAdjuster.setInterval(interval);
		LOGGER.info("FetchAdjuster.setInterval() interval = " + interval);
	}

}
